from decimal import Decimal
from django.shortcuts import render

# Create your views here.
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.generics import CreateAPIView
from django_redis import get_redis_connection
from goods.models import SKU
from orders.serializers import OrderSettlementSerializer, OrderCommitSerializer


class OrderCreateView(CreateAPIView):
    """
    订单保存
    """
    permission_classes = [IsAuthenticated]

    serializer_class = OrderCommitSerializer


class OrderSettlementView(APIView):
    """
    订单管理
    """
    permission_classes = [IsAuthenticated]

    def get(self, request):
        """
        获取购物车的信息
        """
        # 获取用户信息
        user = request.user

        # 创建reids 连接
        redis_conn = get_redis_connection('cart')
        # 获取redis中购物城的信息
        redis_cart = redis_conn.hgetall('cart_%s' % user.id)
        redis_cart_select = redis_conn.smembers('cart_selected_%s' % user.id)

        # 生成勾选的商品信息
        cart = {}
        for sku_id in redis_cart_select:
            cart[int(sku_id)] = int(redis_cart[sku_id])

        # 根据id 获取商品信息
        skus = SKU.objects.filter(pk__in=cart.keys())

        for sku in skus:
            sku.count = cart[sku.id]

        # 定义运费
        freight = Decimal('10.00')

        serializer = OrderSettlementSerializer({'freight': freight, 'skus': skus})
        return Response(serializer.data)
